import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { CmdOption } from "../typings/index.js";
import { UnityHelper } from "./UnityHelper.js";
import { Record } from "./Record.js";
import { toolchain } from "../toolchain.js";
import { Relatives } from "./Relatives.js";
import { HardCodeCollector } from "./HardCodeCollector.js";

export class GenerateStriper {
    public async removeUseless(option: CmdOption, ext: string | null, r: Relatives, checkHardCodeUse: boolean): Promise<void> {
        // 收集用到的guid
        //#region 
        const usedGUIDMap = await UnityHelper.collectUsedGUID(option.projectRoot);
        //#endregion

        if (toolchain.opts.cfg != null) {
            // 部分写死保留的prefab
            if (toolchain.opts.cfg.keep != null) {
                for (const k of toolchain.opts.cfg.keep) {
                    const keeps = await fg(k, { cwd: toolchain.opts.projectRoot });
                    for (const f of keeps) {
                        if (f.endsWith('.meta')) {
                            const guid = await UnityHelper.readGUID(path.join(toolchain.opts.projectRoot, f))
                            usedGUIDMap[guid] = [];
                        }
                    }
                }
            }
        }

        // 采集代码中所有硬编码字符串
        //#region 
        await HardCodeCollector.ensureData();
        //#endregion

        let cnt = 0;
        const assetsRoot = path.join(option.projectRoot, 'Assets');
        const files = await fg(`**/*${ext}`, { cwd: assetsRoot, ignore: ['IGSoft_Resources/**/*.*', 'Spine Examples/**/*.*', 'TextMesh Pro/**/*.*', 'Third/**/*', 'AssetSources/map/**/*.*'] });
        for (const f of files) {
            const file = path.join(assetsRoot, f);
            // if (f.includes('fightBuff')) {
            //     console.log('bbb');
            // }
            const guid = await UnityHelper.readGUID(file + '.meta');

            if (!usedGUIDMap[guid]) {
                // 未被直接引用，再检查是否被代码中使用
                if (checkHardCodeUse) {
                    const usedByHardcode = HardCodeCollector.isUsed(file);
                    if (usedByHardcode) continue;
                }
                
                if (!r.isUsed || r.isRelated(guid)) {
                    await r.collect(file);
                    await fs.unlink(file);
                    await fs.unlink(file + '.meta');
                    await Record.Instance.recordGUID(guid, file);
                    console.log(file);
                    cnt++;
                }
            }
        }

        console.log(`${cnt} ${ext} removed`);
    }
}
